package com.clms.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clms.common.R;
import com.clms.system.mapper.OperLogMapper;
import com.clms.system.pojo.entitry.SysOperLog;
import com.clms.system.pojo.util.WebUtil;
import com.clms.system.pojo.vo.OperLogVo;
import com.clms.system.service.OperLogService;
import org.apache.commons.lang3.StringUtils;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;

/**
 * @program: clms-third
 * @description:
 * @author: 大鱼
 * @create: 2021-07-22 18:05
 **/
@Service
public class OperLogServiceimpl implements OperLogService {
    @Autowired
    OperLogMapper operLogMapper;
    @Override
    public R operLogTable(Integer currentPage, Integer pageSize, OperLogVo operLogVo) {
        System.out.println(operLogVo);
        System.out.println(pageSize);
        System.out.println(currentPage);
        Page<SysOperLog> page = new Page<>(currentPage,pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(operLogVo.getStartDate()))
        {
            queryWrapper.like("oper_name", operLogVo.getOperName());
        }

        if (StringUtils.isNotEmpty(operLogVo.getStartDate())) {
            queryWrapper.ge("creat_time", operLogVo.getStartDate());
        }
        if (StringUtils.isNotEmpty(operLogVo.getEndDate())) {
            queryWrapper.le("creat_time",operLogVo.getEndDate());
        }
        operLogMapper.selectPage(page, queryWrapper);
        System.out.println(page);
        return R.ok().put("operlogs",page.getRecords()).put("total",page.getTotal());
    }

    @Override
    public R removerById(Integer operlogId) {
        operLogMapper.deleteById(operlogId);
        return R.ok().message("删除成功");
    }

    @Override
    public R exportlogs() {
//        String path = session.getServletContext().getRealPath("/fiel");//服务器位置
        List<SysOperLog> operLogs = operLogMapper.selectList(null);//获取所有信息
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();//创建一个文件
        HttpServletResponse response = WebUtil.getResponse();//
        XSSFSheet sheet = xssfWorkbook.createSheet("日志");//excel里面的表名
        Class operLog = SysOperLog.class;//通过反射获取所对象
        Field[] fields = operLog.getDeclaredFields();//反射获取所有属性
        for (int i=0; i < operLogs.size(); i++) {//循环获取每一个对象
            XSSFRow rows = sheet.createRow(i);//创建行
            TreeMap map = JSON.parseObject(JSON.toJSONString(operLogs.get(i)), TreeMap.class);//将对象转换为map 便于对象值
            int j = 1;//循环属性存入单元格
            for (Field field : fields) {
                field.setAccessible(true);//可以获取私有属性
//              field.getName();获取属性名
                rows.createCell(j-1).setCellValue(String.valueOf(map.get(field.getName())));//第j-1个单元格存入对象属性（防止乱序）
                j++;
            }
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("D:Log.xlsx");//文件位置暂时写死（会自动生成）
            xssfWorkbook.write(fileOutputStream);//写入对象
            fileOutputStream.flush();//属性流
            fileOutputStream.close();//关闭流
            response.setCharacterEncoding("utf-8");//文件下载
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("员工表.xlsx", "utf-8"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().message("导入成功");
    }

    @Override//导入
    public R importlogs() {
        File file = new File("D:Log.xlsx");//导入位置
        XSSFWorkbook workbook = new XSSFWorkbook();//新建
        XSSFSheet sheet = workbook.getSheetAt(0);
        List<SysOperLog> list = new ArrayList<>();//存储所有数据批量存储
        int lastrownum = sheet.getLastRowNum();//获取excel行数
        for (int i = 0; i < lastrownum; i++) {
            XSSFRow row = sheet.getRow(i);//获取行
            if (row != null) {
                List<String> listrow = new ArrayList<>();
                short cellnum = row.getLastCellNum();//改行单元格数
                for (int j = 0; j < cellnum; j++) {//循环存储数据
                    XSSFCell cell = row.getCell(j);
                    if (cell != null) {
                        //cell.setCellType(cell.CELL_TYPE_STRING);//设置文本格式然后在转换
                        String value= cell.getStringCellValue();
                        if(value!=null&&!"".equals(value))
                        {
                            listrow.add(value);//单元格信息录入
                        }
                    }
                }

                if(listrow!=null&&listrow.size()!=0)//list<SysOperlog> 存储数据
                {
                    SysOperLog operLog=new SysOperLog();
                    list.add(operLog);
                }
            }
        }
        try {
            workbook.close();//关闭流
          //  operLogMapper.insertall(list);批量存储
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
